package SM::Server::Packet;

use warnings;
use strict;

use Data::Dumper::Simple;

use SM::Constants;

sub new {
	my ( $class, $arg_ref ) = @_;

	#print Dumper($arg_ref);

	my $self = bless {
		raw_data => $arg_ref->{raw_data},
		client   => $arg_ref->{client},
		username => $arg_ref->{username},
	}, $class;

	return $self;
}

# Map of actions for decoding incoming packets
my %packet_map = (    
	( AVATAR . AVATAR_LOCATION ) => 'SM::Server::Packet::In::Avatar::Location',
	( AVATAR . AVATAR_AUTHREQ )  => 'SM::Server::Packet::In::Avatar::AuthReq',
	( CHAT . CHAT_MESSAGE )      => 'SM::Server::Packet::In::Chat::Message',
);

# Decodes incoming packest and returns the appropriate object
sub decode_packet {
	my ( $class, $arg_ref ) = @_;
	my $packet;

	my $data = $arg_ref->{raw_data};
	print Dumper($data);
	my ( $data_type, $sub_type ) = unpack "CC", $data;

	#print Dumper($data_type, $sub_type);

	if ( defined($data_type) && defined($sub_type) ) {
		$arg_ref->{data_type} = $data_type;
		$arg_ref->{sub_type}  = $sub_type;
		$arg_ref->{data}      = $data;
		$arg_ref->{client}    = $arg_ref->{client};
		$arg_ref->{username}  = $arg_ref->{username};

		my $types = $data_type . $sub_type;

		#print Dumper(AVATAR . AVATAR_LOCATION);
		#print Dumper($data_type . $sub_type);

		if ( defined( $packet_map{$types} ) ) {
			$packet = $packet_map{$types}->new($arg_ref);
		}
		return $packet;
	}
	else {
		return undef;
	}

}

sub get_data_type {
	my ($self) = @_;
	return $self->{data_type};
}

sub get_sub_type {
	my ($self) = @_;
	return $self->{sub_type};
}

sub get_raw_data {
	my ($self) = @_;
	return $self->{raw_data};
}

sub get_data {
	my ($self) = @_;
	return $self->{data};
}

sub get_username {
	my ($self) = @_;
	return $self->{username};
}

sub get_session_id {
	my ($self) = @_;
	return $self->{client};
}

1;
